#include "stdafx.h"
#include "World.h"


CWorld::CWorld()
	: m_state(DAY)
{
	m_startTime = time(NULL);
}

void CWorld::AddDwarf(std::shared_ptr<CDwarf> pDwarf)
{
	m_pDwarf = pDwarf;
}

void CWorld::ExecuteCommands(std::vector<std::string> &  commands)
{
	if (commands.size() == 1)
	{
		ExecuteCommand(commands[0]);
	}
	else
	{
		time_t t = time(NULL);
		if (commands[1] == CalculateCurrWorldState())
		{
			while (true)
			{
				ExecuteCommand(commands[2]);
				time_t currTime = time(NULL);
				if (difftime(currTime, t) > 5)
					break;
			}
		}
		else
		{
			std::cout << "Now is not " << commands[1] << std::endl;
		}
	}
}

const std::string CWorld::CalculateCurrWorldState()
{
	time_t currTime = time(NULL);
	currTime -= m_startTime;
	int integer = currTime / 5;

	if (((integer % 2) == 0) && (double(integer) != (currTime / 5.0)))
		return DAY;
	else
		return NIGHT;
}

void CWorld::ExecuteCommand(std::string const & command)
{
	if (command == ATTACK)
		m_pDwarf->Attack();
	else if (command == BACKWARD)
		m_pDwarf->SetDirection(BACKWARD);
	else if (command == FORWARD)
		m_pDwarf->SetDirection(FORWARD);
	else if (command == GO)
		m_pDwarf->Go();
	else if (command == LEFT)
		m_pDwarf->SetDirection(LEFT);
	else if (command == RIGHT)
		m_pDwarf->SetDirection(RIGHT);
	else if (command == SAY)
		m_pDwarf->Say();
	else if (command == STOP)
		m_pDwarf->Stop();
	else if (command == WORK)
		m_pDwarf->Work();
}
